#!/usr/bin/env python
#-*- coding:utf-8 -*-

import gtk
import gobject
import cairo

from ByteManip import *
from VisualBit import *


ANIM_STEPS          = 40
ANIM_TOTAL_TIME_MS  = 500

ANIM_STEP_INC       = 1.0 / ANIM_STEPS
ANIM_STEP_TIME      = ANIM_TOTAL_TIME_MS / ANIM_STEPS


class VisualByte(gtk.HBox):
    
    def __init__(self):
        gtk.HBox.__init__(self)
    
        for i in range(8):
            obj_name = "bit" + str( i+1 )
            
            obj = VisualBit()
            setattr( self, obj_name, obj )
            self.pack_end( obj )

            obj.connect_after( "expose-event", self.on_after_paint )
        
        self.set_spacing( 4 )
        self.show()
        self.set_decimal(0)

        self.anim_running = False
        self.anim_step = 0.0
        self.riscado = False

    
    def get_bit_ctrl(self, bit):
        return getattr( self, "bit" + str(bit) )
    
    
    def set_byte(self, byte):
        for i in range(8):
            self.get_bit_ctrl( i+1 ).set_bit( byte.get_bit(i+1) )


    def set_decimal(self, x):
        self.set_byte( Byte(x) )


    def un_risca(self):
        self.riscado = False
        
    def risca(self):
        self.riscado = True

        self.anim_running = True
        self.anim_step = 0.0

        gobject.timeout_add( ANIM_STEP_TIME, self.on_animate )


    def on_animate(self):
        self.anim_step += ANIM_STEP_INC
        
        for i in range(8):
            self.get_bit_ctrl( i+1 ).queue_draw()
        
        if self.anim_step >= 1.0:
            self.anim_running = False
            return False
        else:
            return True
        
        
    def on_after_paint(self, obj, event):
        if not self.riscado:
            return True

        dw = event.window
        
        cr = dw.cairo_create()

        clip = event.area
        cr.rectangle( clip.x, clip.y, clip.width, clip.height )
        cr.clip()
        
        w = obj.get_allocation().width
        h = obj.get_allocation().height

        if self.anim_running:
            cr.set_source_rgba( 1.0, 0, 0, self.anim_step * 0.7 )

            w = self.anim_step * w
            h = self.anim_step * h
        else:
            cr.set_source_rgba( 1.0, 0, 0, 0.7 )
            
        cr.set_line_width( self.anim_step * 2.5 )
        cr.move_to( 2, 2 )
        cr.line_to( w-4, h-4 )
        cr.stroke()
        
        return True
        
